<?php

namespace App\Models\hwtc;
use Illuminate\Database\Eloquent\Model;
use Cache;
class Apipermission extends Model
{
    protected $table = 'api_permissions';
    protected $guarded = [];

    public function apiroles ()
    {
        // 多对多的关系（一个权限赋予了多个角色）
        return $this->belongsToMany('App\Models\hwtc\Apiroles','api_permission_role','api_permission_id','api_role_id');

    }


    static function getpermissions(){
        $permissions=self::orderBy('model')->get();
        return $permissions;
    }


    public function children()
    {
        return $this->hasMany(Apipermission::class, 'pid', 'id');
    }

    public function parent()
    {
        return $this->belongsTo(Apipermission::class, 'pid', 'id');
    }

    static function clear()
    {
        Cache::forget('system_permissions');
        Cache::forget('system_children_permissions');
    }

    static function get_permissions()
    {
        $permissions = Cache::rememberForever('system_permissions', function () {
            return self::with([
                'children' => function ($query) {
                    $query->orderBy('model');
                    $query->with([
                        'children' => function ($query) {
                            $query->orderBy('model');
                        }
                    ]);
                },
            ])->where('pid', 0)->orderBy('model')->get();
        });

        return $permissions;
    }

    static function get_children()
    {
        $children_permissions = Cache::rememberForever('system_children_permissions', function () {
            return self::with([
                'children' => function ($query) {
                    $query->orderBy('pid');
                }
            ])->where('pid', 0)->orderBy('model')->get();
        });

        return $children_permissions;
    }

    /**
     * 检查是否有子栏目
     */
    static function check_children($id)
    {
        $permission = self::with('children')->find($id);
        if ($permission->children->isEmpty()) {
            return true;
        }
        return false;
    }
}
